package com.ybwh.springboot2.common.enumhub;

import io.github.lukehutch.fastclasspathscanner.FastClasspathScanner;
import io.github.lukehutch.fastclasspathscanner.scanner.ScanResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>
 * 枚举集中管理
 * </p>
 *
 * @author fanbeibei
 * @version 1.0.0
 * @date 2022/4/2 14:39
 */
@Slf4j
@Component
public class EnumHub implements ApplicationListener {
    private static ConcurrentHashMap<String, Class<? extends CodeTextEnum>> currEnumMap = new ConcurrentHashMap<>();

    private static ConcurrentHashMap<String, Set<Class<? extends CodeTextEnum>>> enumMap = new ConcurrentHashMap<>();

    @Value("${enum.packages}")
    private String enumPackages;


    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        if (!(applicationEvent instanceof ContextRefreshedEvent)) {
            return;
        }

        initEnumMap(((ContextRefreshedEvent) applicationEvent).getApplicationContext());
    }

    private synchronized void initEnumMap(ApplicationContext applicationContext) {
        Set<Class<? extends CodeTextEnum>> restClasses = new HashSet<>();
        ScanResult result = new FastClasspathScanner(enumPackages.split(",")).matchClassesImplementing(CodeTextEnum.class, e -> restClasses.add(e)).scan();
        if (CollectionUtils.isEmpty(restClasses)) {
            return;
        }

        for (Class<? extends CodeTextEnum> ec : restClasses) {

            EnumId ei = ec.getAnnotation(EnumId.class);
            if (null == ei) {
                throw new IllegalStateException("NO EnumId on enum  "+ec.getName());
            }

            Class<? extends CodeTextEnum> old = currEnumMap.get(ei.value());
            if (null != old) {
                int oldVersion = getEnumVersion(old);
                int currVersion = getEnumVersion(ec);


                if (currVersion == oldVersion) {
                    throw new IllegalStateException("Duplex enum version for enumcode [" + ei.value() + "], one enum is " + old.getName() + ",other  enum  is" + ec.getName());
                }

                if (currVersion > oldVersion) {
                    currEnumMap.put(ei.value(), ec);
                }


            } else {
                currEnumMap.put(ei.value(), ec);
            }


        }
    }

    private int getEnumVersion(Class<? extends CodeTextEnum> old) {
        EnumVersion oldEnumVersion = old.getAnnotation(EnumVersion.class);
        if (null != oldEnumVersion) {
            return oldEnumVersion.value();
        }


        return 0;

    }

    public static Class<? extends CodeTextEnum> getEnumClass(String enumId) {
        return currEnumMap.get(enumId);
    }


    public static List<CodeTextEnumView> getCodeTextEnumViewList(String enumId) {
        Class<? extends CodeTextEnum> ec = currEnumMap.get(enumId);
        if (null == ec) {
            return Collections.EMPTY_LIST;
        }


        return CodeTextEnumUtils.getCodeTextEnumViewList(ec);
    }


}
